//
//  SettingViewController.swift
//  GZMarathon
//
//  Created by apple on 2021/11/11.
//

import UIKit
import SVProgressHUD
class SettingViewController: UIViewController {

    @IBOutlet weak var nameTF: UITextField!
    
    @IBOutlet weak var noticeLabel: UILabel!
    
    

    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "设置名称"
        noticeLabel.isHidden = true
        nameTF.delegate = self
        nameTF.clearButtonMode = .always
        
        nameTF.text = GZCurrentUser.shared.currentUser?.account_name
        
        let btn=UIButton(frame:CGRect(x: 0, y: 0, width: 60, height: 30))

        btn.setTitle("保存",for:.normal)
        btn.setTitleColor( UIColor("#666666"), for: .normal)
       
        btn.addTarget(self, action: #selector(rightClick), for: .touchUpInside)
        let item=UIBarButtonItem(customView: btn)

        self.navigationItem.rightBarButtonItem = item
        
        
        
    }
    
    @objc func rightClick(){
        guard let text = nameTF.text else {
            SVProgressHUD.showError(withStatus: "请输入用户名")
            return
        }
        
        if text.count == 0 {
            SVProgressHUD.showError(withStatus: "请输入用户名")
            return
        }
        
        if text.count > 9 {
            SVProgressHUD.showError(withStatus: "最多输入九个字符")
            return
        }
        
        
        
        
        ApiLoadingProvider.request(EBAPI.updateCurrent(account_name: text), model: BaseModel.self) { model, isSuccess in
            
            guard let msg = model?.message else{
                SVProgressHUD.showError(withStatus: "修改失败, 请稍后再试")
                return
            }
            
            if msg == "成功"{
                SVProgressHUD.showSuccess(withStatus: "修改成功")
                GZCurrentUser.shared.currentUser?.account_name = text
                self.navigationController?.popViewController(animated: true)
            }else{
                SVProgressHUD.showError(withStatus: msg)

            }
        }
        
        
    }


}

extension SettingViewController: UITextFieldDelegate{
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        guard let text = textField.text else {
            noticeLabel.isHidden = true
            return true
        }
        
        if text.count > 9 {
            noticeLabel.isHidden = false
        }else{
            noticeLabel.isHidden = true
        }
        
        return true
    }
    
}
